import 'package:flutter/material.dart';
import 'dart:math' as math;
import 'package:provider/provider.dart';
import '../services/alger_api_service.dart';
import '../models/song.dart';
import '../services/music_player_service.dart';
import '../utils/util.dart';
import '../widgets/mini_player_widget.dart';
import '../widgets/player_sheet_widget.dart';

class AlgerPlaylistDetailScreen extends StatefulWidget {
  final String playlistId;
  final String playlistName;
  final String coverImgUrl;
  const AlgerPlaylistDetailScreen({
    super.key,
    required this.playlistId,
    required this.playlistName,
    required this.coverImgUrl,
  });

  @override
  State<AlgerPlaylistDetailScreen> createState() => _AlgerPlaylistDetailScreenState();
}

class _AlgerPlaylistDetailScreenState extends State<AlgerPlaylistDetailScreen> {
  final AlgerApiService _api = AlgerApiService();
  List<Song> _tracks = [];
  bool _loading = true;
  String? _description;
  final ScrollController _introScrollController = ScrollController();

  @override
  void initState() {
    super.initState();
    _loadTracks();
  }

  Future<void> _loadTracks() async {
    setState(() => _loading = true);
    try {
      final tracks = await _api.fetchPlaylistTracks(widget.playlistId);
      final desc = await _api.fetchPlaylistDescription(widget.playlistId);
      setState(() {
        _tracks = tracks;
        _description = desc;
      });
    } catch (e) {
      debugPrint('加载歌单详情失败: $e');
    } finally {
      if (mounted) setState(() => _loading = false);
    }
  }

  @override
  void dispose() {
    _introScrollController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final playerService = Provider.of<MusicPlayerService>(context, listen: false);
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.playlistName),
        backgroundColor: Colors.white
      ),
      body: _loading
          ? const Center(child: CircularProgressIndicator())
          : LayoutBuilder(
              builder: (context, constraints) {
                final isWide = CommonUtils.isWideScreen(context);
                // 根据可用高度自适应封面大小，避免左列溢出
                final availableHeight = constraints.maxHeight - 32; // 去除上下 padding
                final coverSize = math.max(180.0, math.min(300.0, availableHeight - 190.0));
                final cover = ClipRRect(
                  borderRadius: BorderRadius.circular(12),
                  child: SizedBox(
                    width: coverSize,
                    height: coverSize,
                    child: Image.network(
                      widget.coverImgUrl,
                      fit: BoxFit.cover,
                      filterQuality: FilterQuality.high,
                    ),
                  ),
                );
                final intro = Container(
                  padding: const EdgeInsets.all(12),
                  decoration: BoxDecoration(
                    color: Colors.grey[100],
                    borderRadius: BorderRadius.circular(12),
                    border: Border.all(color: Colors.grey[300]!),
                  ),
                  constraints: const BoxConstraints(minHeight: 160),
                  child: Scrollbar(
                    controller: _introScrollController,
                    thumbVisibility: true,
                    child: SingleChildScrollView(
                      controller: _introScrollController,
                      primary: false,
                      physics: const BouncingScrollPhysics(),
                      child: Text(
                        (_description ?? '').isNotEmpty ? _description! : '暂无简介',
                        style: const TextStyle(fontSize: 13, color: Colors.black87, height: 1.5),
                      ),
                    ),
                  ),
                );

                final tracksList = ListView.separated(
                  padding: const EdgeInsets.only(top: 4, bottom: 12),
                  itemCount: _tracks.length,
                  itemBuilder: (context, index) {
                    final s = _tracks[index];
                    return ListTile(
                      dense: true,
                      contentPadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
                      leading: s.albumImageUrl != null && s.albumImageUrl!.isNotEmpty
                          ? ClipRRect(
                              borderRadius: BorderRadius.circular(6),
                              child: Image.network(
                                s.albumImageUrl!,
                                width: 48,
                                height: 48,
                                fit: BoxFit.cover,
                                filterQuality: FilterQuality.medium,
                              ),
                            )
                          : const Icon(Icons.music_note),
                      title: Text(s.name),
                      subtitle: Text(s.artistsString),
                      onTap: () async {
                        await playerService.setPlaylist(_tracks, startIndex: index);
                      },
                    );
                  },
                  separatorBuilder: (_, __) => const Divider(height: 1, thickness: 0.5, color: Colors.black12),
                );

                if (isWide) {
                  return Padding(
                    padding: const EdgeInsets.all(16),
                    child: Row(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        SizedBox(
                          width: 320,
                          child: SingleChildScrollView(
                            child: Column(
                              children: [
                                cover,
                                const SizedBox(height: 12),
                                SizedBox(height: 180, child: intro),
                              ],
                            ),
                          ),
                        ),
                        const SizedBox(width: 24),
                        Expanded(child: tracksList),
                      ],
                    ),
                  );
                } else {
                  return Padding(
                    padding: const EdgeInsets.all(16),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Expanded(child: tracksList),
                      ],
                    ),
                  );
                }
              },
            ),
      // 底部迷你播放器（仅当有正在播放的歌曲时显示）
      bottomNavigationBar: Consumer<MusicPlayerService>(
        builder: (context, svc, child) {
          if (svc.currentSong == null) return const SizedBox.shrink();
          return MiniPlayerWidget(onTap: _showPlayerSheet);
        },
      ),
    );
  }

  void _showPlayerSheet() {
    showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      backgroundColor: Colors.transparent,
      constraints: const BoxConstraints(
        maxWidth: double.infinity,
        maxHeight: double.infinity,
      ),
      useSafeArea: true,
      builder: (context) => const PlayerSheetWidget(),
    );
  }
}
